<template>
  <div>
    <el-form
      :model="form"
      ref="addForm"
      :rules="rules"
      label-position="top"
      
      class="demo-ruleForm service_form"
    >
      <el-form-item v-if="isShow" prop="userIds" :label="$t('common.label.addMember')" required>
        <form-user
          :field="userIds"
          v-model="form.userIds"
          max="10"
          multiple
          :isJudge="'service'"
          :type-service-provider="0"
        />
      </el-form-item>
      <el-form-item prop="tagList" :label="isShow ? $t('common.base.belongProvieder') : $t('common.label.belongsToDepartment')" required>
        <biz-team-select
          v-if="flag"
          ref="teamSelect"
          :value="form.tagList"
          :type-service-provider="isServiceProvider"
          collapse
          multiple
          @input="update"
        />
      </el-form-item>

      <el-form-item :label="$t('common.base.role')" prop="role" required>
        <div class="role-box">
          <el-select
            v-model="form.role"
            :placeholder="$t('common.base.pleaseSelect')"
            multiple
            @change="roleChange"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>

          <el-checkbox v-if="isShow && !isProviderSign" @change="getRoleList" v-model="isChecked">{{$t('common.fields.moreRole.displayName')}}</el-checkbox>
        </div>
      </el-form-item>
    </el-form>

    <!-- start 角色 tips -->
    <div v-if="isShow" class="role-txt-box" :class="{ 'warning-txt': isChecked }">
      {{
        !isChecked
          ? $t('serviceProvider.anewSelectRole')
          : $t('serviceProvider.allPermission')
      }}
    </div>
    <div v-else class="role-txt-box">{{$t('serviceProvider.anewSelectRole_1')}}</div>
    <!-- end 角色 tips -->

    <!-- start 操作须知 -->
    <div v-if="isShow" class="tips">
      {{$t('serviceProvider.optTip_1[0]')}}<br />
      {{$t('serviceProvider.optTip_1[1]')}}<br />
      {{$t('serviceProvider.optTip_1[2]')}}<br />
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{$t('serviceProvider.optTip_1[3]')}}<br />
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{$t('serviceProvider.optTip_1[4]')}}<br />
      {{$t('serviceProvider.optTip_1[5]')}}<br />
      {{$t('serviceProvider.optTip_1[6]')}}<br />
      <el-checkbox v-model="isNotice">
          {{$t('serviceProvider.optTip_1[7]')}}
      </el-checkbox>
    </div>
    
    <div class="tips" v-else>
        {{$t('serviceProvider.optTip_2[0]')}}<br />
        {{$t('serviceProvider.optTip_2[1]')}}<br />
        {{$t('serviceProvider.optTip_2[2]')}}<br />
        {{$t('serviceProvider.optTip_2[3]')}}<br />
      <el-checkbox v-model="isNotice">
          {{$t('serviceProvider.optTip_2[4]')}}
      </el-checkbox>
    </div>
    <!-- end 操作须知 -->

  </div>
</template>

<script>
import { providerRole, getRoleTree, bindUser,moveUserToTag } from "@src/api/serviceProviderApi";

export default {
  name: "service-add-member",
  props: {
      isShow: {
          type: Boolean,
          require: true
      }
  },
  data() {
    let validateUser = (rule, value, callback) => {
      if (!this.form.userIds) {
        callback(new Error(this.$t('common.placeholder.selectMember_1')));
      }
      if (this.form.userIds && !this.form.userIds.length) {
        callback(new Error(this.$t('common.placeholder.selectMember_1')));
      } else {
        callback();
      }
    };
    let validateTags = (rule, value, callback) => {
      if (!this.form.tagList.length) {
        callback(new Error(this.$t('common.placeholder.selectServiceProvider')));
      } else {
        callback();
      }
    };
    let validateRole = (rule, value, callback) => {
      if (!this.form.role.length) {
        callback(new Error(this.$t('common.placeholder.selectRole')));
      } else {
        callback();
      }
    };
    return {
      userIds: {
        displayName: this.$t('common.base.member'),
        fieldName: "userIds",
        formType: "user",
        isNull: 0,
      },
      // 表单内容
      form: {
        userIds: [],
        tagList: [],
        role: [],
      },
      rules: {
        userIds: [
          {
            required: true,
            validator: validateUser,
            trigger: ["blue", "change"],
          },
        ],
        tagList: [
          {
            required: true,
            validator: validateTags,
            trigger: ["change", "blue"],
          },
        ],
        role: [
          {
            required: true,
            validator: validateRole,
            trigger: ["change", "blue"],
          },
        ],
      },
      // 更多角色
      isChecked: false,
      roles: [], // 角色列表
      isNotice: false, // 操作须知

      isServiceProvider: 1,
      flag:true
    };
  },
  watch:{
      isShow(n, o){
          this.isServiceProvider = this.isShow ? 1 : 0;

          this.isChecked = false;
          this.isNotice = false;
          this.$refs.addForm.resetFields();

          this.getRoleList();

          this.flag = false;
          this.$nextTick(()=>{
              this.flag = true
          })
      }
  },
  computed: {
    // 当前账号是否存在服务商部门
    isProviderSign(){
      return sessionStorage.getItem('isProviderSign') == 1;
    }
  },
  mounted(){
      this.getRoleList();
  },
  methods: {
    async getRoleList() {
      if (!this.isChecked && this.isShow) {
        await providerRole().then((r) => {
          this.roles = r.data;
        });
      } else {
        getRoleTree().then((result) => {
          if (
            !result ||
            !result.data ||
            !result.data.children ||
            result.data.children.length < 2
          ) {
            return false;
          }
          if (result.data.children[1].type === "assigned") {
            let roles = result.data.children[1].children;
            this.roles = roles.map((role) => ({
              name: role.roleName,
              id: role.roleId,
            }));
          }
        });
      }
    },
    //  所属服务商选择
    update(e) {
      this.form.tagList = e;
      this.$refs['addForm'].clearValidate()
    },
    //   角色选择
    roleChange(e) {
      this.form.role = e;
      this.$forceUpdate();
    },
    // 添加操作
    addMemberSubmit(userIds) {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
            if(!this.isNotice) return this.$platform.alert(this.$t('common.placeholder.readExplainAndAgree'));

            let opt = {
                userIds: this.isShow ? this.form.userIds.map(x=>x.userId) : userIds,
                roleIds: this.form.role,
                tagIds: this.form.tagList.map(x=>x.id)
            }

            const fetch = await this.isShow ? bindUser(opt) : moveUserToTag(opt);

            fetch.then(res=>{
                const { status, data, message } = res;
                if(status !== 0) return this.$platform.alert(message);

                this.$emit('submit');
                this.isChecked = false;
                this.isNotice = false;
                this.$refs.addForm.resetFields();
            })
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item:last-child {
  margin-bottom: 6px;
}

.role-box {
  display: flex;
  align-items: center;
  .el-select {
    flex: 1;
  }
  .el-checkbox {
    margin-left: 10px;
  }
}

.role-txt-box {
  padding: 5px 0 15px 100px;
  margin: 0 24px;
  color: $text-color-secondary;
  border-bottom: 1px solid $border-color-base;
}
.warning-txt {
  color: $color-warning;
}

.tips {
  padding: 10px 24px;
  color: $text-color-secondary;
  line-height: 24px;
}
</style>